// pages/home/search/search.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        onReachBottomLoading: false,
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        screenHeight: app.globalData.screenHeight,
        type:'', //info 普通搜索  brand品牌搜索  explicit综合找车
        infoParam:{
            city: '',
            customItem: '全部',
            historyRecord:[],
            storageFlag: false,
            sliderOption:{
                min:0,
                max:12,
                step:2,
            },
        },
        
        brandParam:{
            brandList:{},//品牌的索引列表
            chooseBrand:{
                brandId:'',
                brandLogo:'',
                brandName:'',
                firstLetter:''
            },
            seriesList:{}, //车系不做单次缓存了，每次都获取吧
        },
        modalName: null,        
        carList:{}, // 对象 页数为key，防止多次触发触底造成数据重复现象
        searchParams:{
          pageNum:1,
          pageSize:6,//默认为6
          total:0, //总条数
          pages: 0, //总页数
          brandId:'',//品牌ID。
          seriesId:'',//车系ID
          city:'',//为全国时不传值
          startMileage:0, //开始里程数。
          endMileage:12, //结束里程数
          startCarAge:0, //开始车龄。
          endCarAge:12, //结束车龄。
          keyword:'', //条件模糊查询。
        },
        userInfo:{accountStatus:0}, // 保护数据
        jumpType:null,
        seriesStatList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        if(undefined != options.etype){
            this.setData({
                type: options.etype
            });
            if ('brand' == options.etype) {
                this.setData({
                    'searchParams.brandId': undefined==options.bid?'':options.bid,
                    'modalName': 1==options.show?'viewModal':null,
                    'jumpType': 1==options.show?'viewModal':null,
                });
            }
        }else{
            // 默认为普通搜索.
            this.setData({
                type: 'info'
            });
        };
        // 检查登录
        this.InitUserStatus();
    },
    infoSearchText(e){
        this.setData({
            'searchParams.keyword': e.detail.value,
            'searchParams.brandId': '',
            'searchParams.seriesId': ''
        });
        this.carCustSearchSeriesStat();
    },
    carCustSearchSeriesStat(){
        let searchParams = {city: this.data.searchParams.city,keyword:this.data.searchParams.keyword};
        // 整理完成进行搜索操作。
        app.sHttp.carCustSearchSeriesStat(searchParams).then(res=>{
            this.setData({
                'seriesStatList':res.seriesStatList
            })
          },err=>{
            this.setData({
                'seriesStatList': []
            })
        })
    },
    clickSeriesStat(e){
        let index = e.currentTarget.dataset.idx;
        let item = this.data.seriesStatList[index]
        this.setData({
            'seriesStatList': [],
            'searchParams.brandId': item.brandId,
            'searchParams.seriesId': item.seriesId,
            'searchParams.keyword': ''
        });
        let self = this;
        setTimeout(() => {
            self.goSearch();
        }, 200);
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        this.setData({
            'userInfo': app.globalData.userInfo
        })
        this.initTypeSearch('init');
    },
    initTypeSearch(type){
        // 参数完成之后进行品牌查询。
        if ('init' != type) {
            this.resetSearchParam();
        }
        switch (this.data.type) {
            case 'info':
                this.loadHistory();
                break;
            case 'brand':
                this.getCarBrandList('init');
                break;
            case 'explicit':
                app.showNoAuthOrNoGrant('功能内测中，暂未开放哦~');
                break;
            default:
                app.showNoAuthOrNoGrant('当前无法为您服务，请重试');
                break;
        }
    },
    resetSearchParam(){
        this.setData({
            carList:{}, // 对象 页数为key，防止多次触发触底造成数据重复现象
            searchParams:{
                pageNum:1,
                pageSize:6,//默认为6
                total:0, //总条数
                pages: 0, //总页数
                brandId:'',//品牌ID。
                seriesId:'',//车系ID
                city:'',//为全国时不传值
                startMileage:0, //开始里程数。
                endMileage:12, //结束里程数
                startCarAge:0, //开始车龄。
                endCarAge:12, //结束车龄。
                keyword:'', //条件模糊查询。
            },
        })
    },
    resetQuery(){
        this.setData({
            'carList':{}, // 对象 页数为key，防止多次触发触底造成数据重复现象
            'searchParams.pageNum': 1,
            'searchParams.total': 1,
            'searchParams.pages': 1,
        })
    },
    onShow: function(){
        if('info' == this.data.type){
            this.loadLocations();
        }
    },
    // 切换搜索方式
    chooseEtype(e){
        if(e.currentTarget.dataset.etype == 'explicit'){
          app.alert('功能内测中，暂未开放~');
          return;
        }
        this.setData({
            type:e.currentTarget.dataset.etype
        });
        this.initTypeSearch();
    },
    // 搜索方式，根据当前搜索的type来区别不同的参数
    goQuery(){
        let searchParams = app.deepCopy(this.data.searchParams);
        // if(searchParams.keyword == '' && this.data.type == 'info'){
        //     app.alert('请输入搜索信息~');
        //     return;
        // }
        this.setData({
            'onReachBottomLoading': true
        })
        searchParams = this.arrangeParams(searchParams);
        searchParams.city == ""? delete searchParams.city:'';
        // 整理完成进行搜索操作。
        app.sHttp.carCustList(searchParams).then(res=>{
            let carList = this.data.carList;
            carList[searchParams.pageNum] = res.result.carList;
            if (0 == res.result.total) {
                app.alert('没有符合条件的车辆~');
                this.setData({
                    'onReachBottomLoading': false
                  })
            }else{
                this.setData({
                    'carList': carList,
                    'searchParams.total':res.result.total,
                    'searchParams.pages': res.result.pages,
                    'modalName': 'viewModal',
                    'onReachBottomLoading': false
                  })
            }
          },err=>{
            app.error(err.msg);
        })
    },
    arrangeParams(searchParams){
        if (this.data.type == 'info') {
            // delete searchParams.brandId;
            // delete searchParams.seriesId;
            if (searchParams.endMileage == this.data.infoParam.sliderOption.max) {
                delete searchParams.endMileage;
                delete searchParams.startMileage;
            }
            if (searchParams.endCarAge == this.data.infoParam.sliderOption.max) {
                delete searchParams.endCarAge;
                delete searchParams.startCarAge;
            };
            return searchParams;
        }else if (this.data.type == 'brand') {
            delete searchParams.endMileage;
            delete searchParams.startMileage;
            delete searchParams.endCarAge;
            delete searchParams.startCarAge;
            delete searchParams.keyword;
            return searchParams;
        }
    },
    // 普通搜索方法-----------------------------------------info
    // 搜索好车。
    searchCardList(e){
        if('' == e.detail.value){
            app.alert('请您输入车辆关键字哦~');
            return;
        }
        this.resetQuery();
        this.setData({
            'searchParams.keyword': e.detail.value
        });
        // 增加内容到
        var searchData = this.data.infoParam.historyRecord;
        if (searchData.indexOf(e.detail.value) == -1) {
            searchData.push(e.detail.value);
            wx.setStorageSync('searchInfoData', searchData);
            this.loadHistory();
        };
        this.goQuery();
    },
    agenHistoryText(e){
        this.setData({
            'searchParams.keyword': e.currentTarget.dataset.infotext
        })
    },
    // 图标点击搜索
    goSearch(e){
        this.resetQuery();
        if('' != this.data.searchParams.keyword){
            var searchData = this.data.infoParam.historyRecord;
            if (searchData.indexOf(this.data.searchParams.keyword) == -1) {
                searchData.push(this.data.searchParams.keyword);
                wx.setStorageSync('searchInfoData', searchData);
                this.loadHistory();
            }
        }
        if(e){
            if(e.currentTarget.dataset.userc){
                if (this.data.type == 'info') {
                    this.setData({
                        'searchParams.brandId':'',
                        'searchParams.seriesId':''
                    })
                }
            }
        }
        this.goQuery();
    },
    // 里程变化
    mileageChange(e){
        this.setData({
            'searchParams.endMileage': e.detail.detail.value
        })
    },
    // 车龄变化
    vehicleAgeChange(e){
        this.setData({
            'searchParams.endCarAge': e.detail.detail.value
        })
    },
    // 加载位置信息
    loadLocations(){
        let city = app.globalData.defaultCity == '全国'?'':app.globalData.defaultCity;
        if (city == this.data.searchParams.city) {
          return;
        }
        this.setData({
          'searchParams.city':'全国'==city?'':city
        });
    },
    // 加载历史搜索关键字
    loadHistory(){
        this.setData({
            'infoParam.historyRecord': wx.getStorageSync('searchInfoData') || [], 
            'infoParam.storageFlag': true
        })
    },
    clearSearchStorage: function () {
        let self = this;
        wx.showModal({
          title: '提醒',
          content: '是否清除全部历史记录',
          success(res) {    
            if (res.confirm) {
                wx.removeStorageSync('searchInfoData')
                self.setData({
                    'infoParam.historyRecord': [],
                    'infoParam.storageFlag': false
                })
            }
          }
        })
    },
    // 品牌搜索方法------------------------------------------------brand
    getCarBrandList(type){
        if ('init' == type) {
            if ('' != this.data.searchParams.brandId) {
                this.goQuery();
                let self = this;
                setTimeout(() => {
                    self.initBrand();
                }, 1500);
            }else{
                this.initBrand();
            }
        }else{
            this.initBrand();
        }
    },
    initBrand(){
        if(null == app.globalData.carBrandList){
            app.sHttp.carBrandList().then(res =>{
                let brandList = {};
                res.brandList.forEach(item =>{
                    if(undefined == brandList[item.firstLetter]){
                        brandList[item.firstLetter] = [item]
                    }else{
                        brandList[item.firstLetter].push(item);
                    }
                });
                app.globalData.carBrandList = brandList;
                this.setData({
                    'brandParam.brandList': brandList
                });
            },err=>{
                app.error(err.msg);
            })
        }else{
            this.setData({
                'brandParam.brandList': app.globalData.carBrandList
            });
        }
    },
    brandClick(e){
        this.resetQuery();
        this.setData({
            'brandParam.chooseBrand': e.detail,
            'brandParam.seriesList': {},
            'searchParams.brandId': e.detail.brandId
        });
        // 获取车系
        app.sHttp.carBrandSeriseList(e.detail.brandId).then(res =>{
            let seriesList = {};
            res.seriesList.forEach(item =>{
                if(undefined == seriesList[item.sname]){
                    seriesList[item.sname] = [item]
                }else{
                    seriesList[item.sname].push(item);
                }
            });
            this.setData({
                'brandParam.seriesList': seriesList,
                'modalName': 'DrawerModalR'
            });
        },err=>{
            app.error(err.msg);
        })
    },
    seriesClick(e){
        let seriesId = "";
        if (null != e.currentTarget.dataset.series) {
            seriesId = e.currentTarget.dataset.series.seriesId;
        }
        this.setData({
            'searchParams.seriesId': seriesId,
            'modalName': null
        });
        // 进行查询
        this.goQuery();
    },
    
    showModal(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        if('viewModal' == this.data.jumpType){
            this.BackPage();
        }else{
            this.resetQuery();
            this.setData({
                modalName: null
            })
        }
    },
    BackPage() {
      var that = this;
      wx.navigateBack({
        delta: 1,
        fail: function(){
          that.toHome();
        }
      });
    },
    toHome(){
      wx.reLaunch({
        url: '/pages/home/home',
      })
    },
    // 跳转到省市选择
    toCitySelector(){
    wx.navigateTo({
        url: '/pages/StSwitchCity/StSwitchCity',
    })
    },
    onReachBottom(){
        if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
            app.alert('没有更多车辆了哦~');
        }else{
            let self = this;
            this.setData({
                'searchParams.pageNum': self.data.searchParams.pageNum+1
            });
            this.goQuery();
        }
    },
    // 跳转到车辆详情页面
    jumpToCardInfo(e){
      let cid = e.currentTarget.dataset.cid;
      wx.navigateTo({
        url: '/pages/card/card?cid=' + cid,
      })
    },
})